<?php
	require_once(dirname(__FILE__)."/../core/safeParam.php");

	class user {
		
  		// Login function.
  		function login($vars){
    		global $admin;
    		global $database;
    		global $db;

    		$username = $vars['username'];
    		$password = $vars['password'];
    		$userID = $database->select("SELECT id FROM config where username = '" . $username . "' and password = '" . md5($password) . "'");
    		$userID = $userID[0]['id'];
    		
    		if ($userID) {
    			$_SESSION['username'] = $username;
      		$_SESSION['password'] = $password;
      		$_SESSION['admin'] = $userID;
				
				if ($userID != 1) {
					$ex = " ?site=". $userID ." ";
      		} 
      		
      		header('location: ../admin/' . $ex . '');
    		} 
			
			$rid = $this->getRestaurantForUser($username, $password);
			
			if ($rid){
				// user is valid for this restaurant;
				$_SESSION['username'] = $username; // not sure this is correct, as it will now have the email address instead of the admin username...
      		$_SESSION['password'] = $password;
      		$_SESSION['admin'] = $rid;
      		$_SESSION['staffUser'] = true; // they are not a normal admin, some permissions don't apply
      		
      		if ($rid != "1") {
      			$ex = "?site=" . $rid;
      		} else {
      			$ex = "";
      		} 
      		
      		header('location: ../admin/' . $ex);
      	} else {
      		header('location: ../admin/index.php?error=wrong');
      	}
  		}

  		function getRestaurantForUser($username, $password){
  			global $database;
  			$query = "select id, email from users where email = '$username' and password = '". md5($password) ."'";
    		$result = $database->select($query);
    		$userID = $result[0]['id'];
    		$email = $result[0]['email'];
 			
 			if (!$userID){
      		return false;
    		}// check if this authenticated user is authorized for administrative functions

			$query = "select rid from options where name = '".$email."_authorized'";
    		$results = $database->select($query);
    		// may be more than one restauarant, but for now, we'll only return the first one, as this is the key use-case.  
    		//In the future, we may ask which restauarant they wish to adminster, or use the same drop-downs as the super-administrator uses...
    		
    		$rid = $results[0]['rid'];
			return $rid; // may be null...
  		}
	
		function logout(){
    		$_SESSION['username'] = "";
    		$_SESSION['password'] = "";
    		$_SESSION['admin'] = "";

    		session_destroy();
    		session_unset();
    		header('location: ../admin/');
  		}
	}
?>
